package main

import (
	"fmt"
	_ "github.com/denisenkom/go-mssqldb"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	_ "github.com/lib/pq"
	"log"
)

func testDb() {
	//MSSQL_HOST='192.168.2.159'
	//MSSQL_USER='qzdata'
	//MSSQL_PASSWORD='qzdata159@Qz'
	engine, err := SqlServerSetUp("keyname11", "qzdata159@Qz", "192.168.2.159", "qzdata", "QZPolicyData", "1433")
	if err != nil {
		fmt.Println("初始化数据库失败")
	} else {
		result, err := engine.Query("select TOP 1 * from ScrapyWebLinkSource")
		if err == nil {
			fmt.Println(result)
			engine.Close()
		} else {
			fmt.Println(err)
		}
	}

}

func SqlServerSetUp(Keyname, dataPwd, dataHost, dataUser, dataName, datePort string) (engine *xorm.Engine, err error) {
	connString := fmt.Sprintf("server=%s;database=%s;user id=%s;password=%s;port=%s;encrypt=disable",
		dataHost,
		dataName,
		dataUser,
		dataPwd,
		datePort)

	engine, err = xorm.NewEngine("mssql", connString)
	if err != nil {
		log.Println("Open connection failed:", connString, err)
		return nil, err
	}

	engine.SetMaxIdleConns(100)
	engine.SetMaxOpenConns(100)

	if err = engine.Ping(); err != nil {
		log.Println("数据库连接失败:", connString, err.Error(), Keyname)
		return nil, err
	} else {
		log.Println("数据库连接成功：", dataHost, Keyname)
	}

	engine.ShowSQL(true)

	return engine, nil
}

func main() {
	testDb()
}
